<template>
  <Result title="您当前正在使用默认密码登录,为了您的安全,请修改密码。">
    <template #extra>
      <Form :model="formState" ref="formRef" layout="vertical" hideRequiredMark="true">
        <FormItem
          name="defaultPassword"
          label="旧密码"
          :labelCol="{ span: 10, offset: 8 }"
          :rules="[{ required: true, message: '密码不能为空' }]"
        >
          <Col span="8" offset="8">
            <InputPassword v-model:value="formState.defaultPassword"></InputPassword>
          </Col>
        </FormItem>
        <FormItem
          name="password"
          label="新密码"
          :labelCol="{ span: 10, offset: 8 }"
          :rules="[
            { required: true, message: '密码不能为空' },
            {
              pattern: new RegExp(
                '^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,18}$'
              ),
              message: '密码为8-18位,应包括数字、小写字母、大写字母、特殊符号4类中至少3类',
            },
          ]"
        >
          <Col span="8" offset="8">
            <InputPassword v-model:value="formState.password"></InputPassword>
          </Col>
        </FormItem>
        <FormItem
          name="repeatPassword"
          label="确认新密码"
          :labelCol="{ span: 10, offset: 8 }"
          :rules="[
            { required: true, message: '两次密码输入不一致', pattern: new RegExp('^' + formState.password + '$') },
          ]"
        >
          <Col span="8" offset="8">
            <InputPassword v-model:value="formState.repeatPassword"></InputPassword>
          </Col>
        </FormItem>
      </Form>
      <Button key="console" type="primary" @click="editHandler">修改</Button>
    </template>
  </Result>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { Result, Button, Form, FormItem, InputPassword, Col } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { editPassword } from '/@/api/sys/password';
import { useUserStoreWithout } from '/@/store/modules/user';
import { ChangePassword } from '/@/api/sys/model/passwordModel';

let formState = reactive<Record<string, any>>({});
const formRef = ref('formRef');
const userStore = useUserStoreWithout();
const { createMessage } = useMessage();

const editHandler = async () => {
  const params: ChangePassword = await formRef.value.validate();
  params.userId = userStore.getUserInfo.userId;

  const res = await editPassword(params);

  if (res === '更新默认密码成功') {
    createMessage.success(res);
    userStore.logout(true);
  } else {
    createMessage.error(res);
  }
};
</script>
